/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: KlinePresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.kline.presenter;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;

import com.bhex.kline.KlineKind;
import com.bhex.kline.widget.TabButtonItem;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.AppUI;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.kline.ui.DepthViewFragment;
import io.bhex.app.kline.ui.KlineFragment;
import io.bhex.app.utils.ShareConfigUtils;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.SP;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.config.ConfigApi;
import io.bhex.sdk.config.bean.ShareConfigBean;
import io.bhex.sdk.invite.InviteApi;
import io.bhex.sdk.invite.bean.InviteResponse;
import io.bhex.sdk.quote.QuoteApi;
import io.bhex.sdk.socket.NetWorkObserver;
import io.bhex.app.kline.bean.PriceDigits;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.quote.bean.TickerListBean;
import io.bhex.sdk.quote.bean.DepthSocketResponse;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BasePresenter;



public class KlinePresenter extends BasePresenter<KlinePresenter.KlineUI> {

    private String[] tabStrs ;


    public KlinePresenter(BaseActivity activity) {
        this.activity = activity;
        tabStrs = new String[]{getString(R.string.kline_fifteen_minutes),
                getString(R.string.kline_one_hour),
                getString(R.string.kline_four_hour),
                getString(R.string.kline_days),
                getString(R.string.string_more),
                getString(R.string.string_depth)};
    }

    public interface KlineUI extends AppUI {


        void showTicker(TickerBean data);

        void getTickerFailed(String msg);

        void setCurrentPriceDigits(PriceDigits response);

        String getExchangeId();

        String getSymbols();

        void setShareConfig(ShareConfigBean response);

        void showShareInfo(InviteResponse response);
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, KlineUI ui) {
        super.onUIReady(activity, ui);
        getShareInfo();
        getShareConfig();
    }


    public ArrayList<TabButtonItem> getKLineTab() {
        ArrayList<TabButtonItem> tabs = new ArrayList<>();
        //TabButtonItem item_15 = new TabButtonItem(tabStrs[0], 1, KLINE_TYPE_MINUTE_FIFTEEN);
        TabButtonItem item_15 = new TabButtonItem(tabStrs[0], 1, "kind_t_15m");
        tabs.add(item_15);

        //TabButtonItem item_1h = new TabButtonItem(tabStrs[1], 1, KLINE_TYPE_HOUR_ONE);
        TabButtonItem item_1h = new TabButtonItem(tabStrs[1], 1, "kind_t_1h");
        tabs.add(item_1h);

        //TabButtonItem item_4h = new TabButtonItem(tabStrs[2], 1, KLINE_TYPE_HOUR_FOUR);
        TabButtonItem item_4h = new TabButtonItem(tabStrs[2], 1, "kind_t_4h");
        tabs.add(item_4h);

        //TabButtonItem item_1d = new TabButtonItem(tabStrs[3], 1, KLINE_TYPE_DAY_ONE);
        TabButtonItem item_1d = new TabButtonItem(tabStrs[3], 1, "kind_t_1d");
        tabs.add(item_1d);

        TabButtonItem item_more = new TabButtonItem(tabStrs[4], 2, "-1");
        tabs.add(item_more);

        TabButtonItem item_depth = new TabButtonItem(tabStrs[5], 3, "kind_depth");
        tabs.add(item_depth);

        /*TabButtonItem item_full = new TabButtonItem("",3);
        tabs.add(item_full);*/

        return tabs;
    }

    public void goKlineFragment() {
        setCurrentFragment(KlineFragment.class, null);
    }

    public void goDepthFragment(){
        setCurrentFragment(DepthViewFragment.class, null);
    }

    private void setCurrentFragment(Class fragmentClass, Bundle bundle) {
        FragmentManager manager = getActivity().getSupportFragmentManager();
        Fragment dstFragment = manager.findFragmentByTag(fragmentClass.getSimpleName());

        List<Fragment> fragments = manager.getFragments();

        FragmentTransaction transaction = manager.beginTransaction();

        if (fragments != null)
            for (Fragment frg : fragments)
                transaction.hide(frg);

        if (dstFragment == null) {
            dstFragment = Fragment.instantiate(getActivity(), fragmentClass.getName(), bundle);
            transaction.add(R.id.main_fragment, dstFragment, fragmentClass.getSimpleName()).commitAllowingStateLoss();
        } else {
            transaction.show(dstFragment).commitAllowingStateLoss();
        }

    }

    /**
     * 获取分享配置
     */
    private void getShareConfig() {
        ConfigApi.getShareConfig(new SimpleResponseListener<ShareConfigBean>(){

            @Override
            public void onSuccess(ShareConfigBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    getUI().setShareConfig(response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }

            @Override
            public ShareConfigBean parserResponse(Handler uiHandler, String response, Class<ShareConfigBean> clazz) {
                if (!TextUtils.isEmpty(response)) {
                    ShareConfigUtils.saveShareConfigData(response);
                }
                return super.parserResponse(uiHandler, response, clazz);
            }
        });
    }

    public void getShareInfo(){
        if (!UserInfo.isLogin()) {
            return;
        }
        InviteApi.inviteShareInfo(new SimpleResponseListener<InviteResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(InviteResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    getUI().showShareInfo(response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getTicker();
        requestDepthData();
    }


    @Override
    public void onPause() {
        super.onPause();
        QuoteApi.UnSubTickers();
        QuoteApi.UnSubDepthData();
    }

    public void getTicker(){
        QuoteApi.SubTicker(getUI().getExchangeId(), getUI().getSymbols(), new NetWorkObserver<TickerListBean>() {
            @Override
            public void onShowUI(TickerListBean response) {
                if (getUI() == null || !getUI() .isAlive() || response == null)
                    return;

                List<TickerBean> datas = response.getData();
                if (datas != null) {
                    for (TickerBean data : datas) {
                        String s = data.getS();
                        if (!TextUtils.isEmpty(s)) {
                            if (s.equals(getUI().getSymbols())) {
                                getUI().showTicker(data);
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(String error) {
            }
        });

    }

    public void requestDepthData(){
        QuoteApi.SubDepthData(getUI().getExchangeId(),  getUI().getSymbols(), new NetWorkObserver<DepthSocketResponse>() {
            @Override
            public void onShowUI(DepthSocketResponse response) {
                if (getUI() == null || !getUI().isAlive() || response == null)
                    return;
                if(response.data != null && response.data.size()>0) {
                    if (response.data.get(0) != null) {
                        boolean bFirst = true;
                        if (response.f != null)
                            bFirst = response.f;
                        response.data.get(0).f = bFirst;
                        EventBus.getDefault().post(response.data.get(0));
                    }
                }
            }

            @Override
            public void onError(String error) {
            }
        });

    }

    /**
     *
     * @param context
     */
    public static void initKind(Context context){
        KlineKind.getInstance().kind_t_map.clear();
        KlineKind.getInstance().kind_t_map.put("kind_t_1fenshi",context.getString(R.string.kline_minutes));
        KlineKind.getInstance().kind_t_map.put("kind_t_1m",context.getString(R.string.kline_one_minute));
        KlineKind.getInstance().kind_t_map.put("kind_t_5m",context.getString(R.string.kline_five_minutes));
        KlineKind.getInstance().kind_t_map.put("kind_t_15m",context.getString(R.string.kline_fifteen_minutes));
        KlineKind.getInstance().kind_t_map.put("kind_t_30m",context.getString(R.string.kline_thirty_minutes));
        KlineKind.getInstance().kind_t_map.put("kind_t_1h",context.getString(R.string.kline_one_hour));
        KlineKind.getInstance().kind_t_map.put("kind_t_2h",context.getString(R.string.kline_two_hour));
        KlineKind.getInstance().kind_t_map.put("kind_t_4h",context.getString(R.string.kline_four_hour));
        KlineKind.getInstance().kind_t_map.put("kind_t_6h",context.getString(R.string.kline_four_hour));
        KlineKind.getInstance().kind_t_map.put("kind_t_12h",context.getString(R.string.kline_twelve_hour));
        KlineKind.getInstance().kind_t_map.put("kind_t_1d",context.getString(R.string.kline_days));

        KlineKind.getInstance().kind_t_map.put("kind_t_1w",context.getString(R.string.kline_weeks));
        KlineKind.getInstance().kind_t_map.put("kind_t_1M",context.getString(R.string.kline_months));

        //MMKVManager.getInstance().loadKind_T_Tag();

        //DebugLog.d("BaseKlineActivity==>:","t_tag=="+KlineFragment.KIND_T);
    }

}
